const Router = require("koa-router");
const router = new Router();
const { poolQuery, pool } = require("../pg/query");

/**
 * @swagger
 * /district/query: # 接口地址
 *   get: # 请求体
 *     description: 用户登入 # 接口信息
 *     tags: [行政区模块] # 模块名称
 *     produces:
 *       - application/json # 响应内容类型
 *     parameters: # 请求参数
 *       - name: adcode
 *         description: 行政区adcode,默认为100000
 *         in: query # 参数的位置，可能的值有 "query", "header", "path" 或 "cookie" 没有formData，但是我加了不报错
 *         type: int
 *       - name: child
 *         description: 是否返回子级，0不返回，1返回；默认为0
 *         in: query
 *         type: string # 可能的值有string、number、file（文件）等
 *       - name: extensions
 *         description: 是否返回行政区边界，base不返回，all返回；默认为base
 *         in: query
 *         type: string # 可能的值有string、number、file（文件）等
 *     responses:
 *       '200':
 *         description: Ok
 *         schema: # 返回体说明
 *           type: 'object'
 *           properties:
 *             code:
 *               type: 'number'
 *             data:
 *               type: 'object'
 *               description: 返回数据
 *             msg:
 *               type: 'string'
 *               description: 消息提示
 *       '400':
 *         description: 请求参数错误
 *       '404':
 *         description: not found
 */

class Result {
  code;
  data;
  msg;

  constructor(code, data, msg) {
    this.code = code;
    this.data = data;
    this.msg = msg;
  }
}

router.get("/query", async (ctx) => {
  let { extensions, child, adcode } = ctx.query;
  adcode = adcode || 100000;
  child = child || "0";
  extensions = extensions || "base";
  const { rows } = await poolQuery(`select id,adcode,citycode,name,center,level${extensions == "all" ? ",ST_AsGeoJSON(the_geom) as geojson" : ""}  from t_district  WHERE adcode = ${adcode};`);
  const res = rows[0];
  const q_r = child == "1" ? await poolQuery(`select id,adcode,citycode,name,center,level from t_district  WHERE parent_id = '${res["id"]}';`) : { rows: [] };
  Object.assign(res, { child: q_r.rows });
  ctx.response.body = new Result(200, res, "请求成功");
});

module.exports = router;
